<template>
  <div class="aa">
    <div class="usermanage">
      <div class="msg">用户管理</div>
      <div class="usermanagebutton">
          <el-button-group class="ml-4">
          <el-button type="primary" :icon="Plus" @click="AddUserManage"/>
          <el-button type="primary" :icon="Delete" @click="handleDelete" />
          </el-button-group>
          <AddUser ref="adduserRef" @on-update="refreshData" />
          <el-button-group class="btn-left">
            <el-tooltip class="box-item" effect="dark" content="显示|隐藏" placement="top">
              <el-button type="primary" :icon="View" ></el-button>
            </el-tooltip>
            <el-tooltip class="box-item" effect="dark" content="复制" placement="top"><el-button type="primary" :icon="Crop"></el-button></el-tooltip>
            <el-tooltip class="box-item" effect="dark" content="Excel" placement="top"><el-button type="primary" :icon="Document"></el-button></el-tooltip>
            <el-tooltip class="box-item" effect="dark" content="输出" placement="top"><el-button type="primary" :icon="Printer"></el-button></el-tooltip>
          </el-button-group>
      </div>
      <div class="table_top">
        <el-input v-model="searchValue" class="input_" placeholder="Please Input" >
        <template #append>
        <el-button :icon="Search" @click="toSearch" />
        </template>
      </el-input>
      </div>
    <el-table 
    ref="multipleTableRef" 
    border 
    tooltip-effect="dark" 
    :data="tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
    style="width: 100%" 
    @selection-change="handleSelectionChange"
    max-height="430"
    :height="356"
    :row-style="{ height: '40px' }"
    v-loading="loading"
    :element-loading-svg="svg"
    class="custom-loading-svg"
    element-loading-svg-view-box="-10, -10, 50, 50"
    >
      <el-table-column type="selection" width="40" />
      <el-table-column fixed label="序号" align="center" min-width="55">
        <template #default="{ $index }">
          {{ ($index + 1) + pageSize * (currentPage - 1) }}
        </template>
      </el-table-column>
      <el-table-column prop="UserId" label="用户名" sortable align="center" min-width="100" show-overflow-tooltip />
      <el-table-column prop="UserName" label="姓名" align="center" min-width="60" show-overflow-tooltip />
      <el-table-column prop="Sex" label="性别" align="center" min-width="55" />
      <el-table-column prop="Degree" label="学历" align="center" min-width="70" show-overflow-tooltip/>
      <el-table-column prop="TelNo" label="电话" align="center" min-width="60" show-overflow-tooltip/>
      <el-table-column prop="CompanyId" label="单位" align="center" min-width="130" show-overflow-tooltip/>
      <el-table-column prop="PositionId" label="职位" align="center" min-width="60" />
      <el-table-column prop="Status" label="状态" align="center" min-width="55" show-overflow-tooltip/>
      <el-table-column prop="EdtByUserId" label="操作员" align="center" min-width="120" show-overflow-tooltip/>
      <el-table-column prop="EdtTime" label="操作时间" sortable align="center" min-width="120" show-overflow-tooltip />
      <el-table-column fixed="right" label="Operations" align="center" width="160">
        <template #default="{ row }">
          <el-tooltip class="box-item" effect="dark" content="编辑" placement="top">
            <el-button link type="primary" :icon="Edit" @click="EditUserManage(row)"></el-button>
          </el-tooltip>
          <el-tooltip class="box-item" effect="dark" content="修改密码" placement="top">
            <el-button link type="primary" :icon="Key" ></el-button>
          </el-tooltip>
          <el-tooltip class="box-item" effect="dark" content="私有权限" placement="top">
            <el-button link type="primary" :icon="Monitor"></el-button>
          </el-tooltip>
          <el-tooltip class="box-item" effect="dark" content="权限全览" placement="top">
            <el-button link type="primary" :icon="View"></el-button> 
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <EditUser ref="edituserRef" @on-update="refreshData"/>
    <div class="table_bottom">
      <Pagination :pageSize="pageSize" :total="total" @getCurrentPage="getCurrentPage"></Pagination>
    </div>
    </div>
  </div>
</template>
  
<script setup>
import { getTableDataAPI } from '@/apis/layout';
import { onMounted,ref,computed } from 'vue'
import {Delete,Edit,Search,Plus,View,Hide,Crop,Promotion,Printer,Document,Key,Monitor } from '@element-plus/icons-vue'
import EditUser from '@/views/Manage/UserManage/EditUser.vue'
import AddUser from '@/views/Manage/UserManage/AddUser.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Pagination from '@/views/Manage/Pagination/Pagination.vue'
import axios from 'axios';

//加载
const loading = ref(true)
const svg = `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `
//定义分页数据.........
const total = ref(0)
const pageSize = ref(1)
const currentPage = ref(1)
const getCurrentPage=(val)=>{
  currentPage.value = val;
}
const tableData = ref( [] )
const gettableData = async () => {
  try {
    loading.value = true; // 开启加载状态
    const res = await getTableDataAPI();
    setTimeout(() => {
      loading.value = false; // 关闭加载状态
      tableData.value = res.data.result;
      total.value = tableData.value.length;
      pageSize.value = 8;
      originalTableData.value = [...tableData.value];
    }, 1000); // 设置最低持续时间为 1 秒
  } catch (error) {
    console.error('获取不到！', error);
  }
};

const selectedRows = ref([]); // 存储选中的多条数据
const selectedRowIds = ref([]); // 存储选中的多条数据的ID
const handleSelectionChange = (selection) => {
  // 更新选中的多条数据
  selectedRows.value = selection;
  // 更新选中的多条数据的ID
  selectedRowIds.value = selection.map((row) => row.Id);
}

// TODO: 查询功能
const searchValue = ref(''); // 存储用户输入的搜索关键词
// 备份原始数据
const originalTableData = ref([]);
// 查询功能
const toSearch = () => {
  loading.value = true; // 显示加载样式
  // 获取用户输入的数据
  const searchKeyword = searchValue.value.toLowerCase();
  
  // 如果没有输入搜索关键词，恢复原始数据
  if (!searchKeyword) {
    setTimeout(() => {
    tableData.value = [...originalTableData.value];
    total.value = tableData.value.length;
    loading.value = false; // 隐藏加载样式
  }, 1000); // 模拟查询耗时 1 秒
    return;
  }
  // 过滤 tableData 中的数据
  const filteredData = originalTableData.value.filter((row) => {
    // 假设你想在用户名列上进行模糊查询
    return row.UserId.toLowerCase().includes(searchKeyword);
  });
  setTimeout(() => {
    // 更新表格数据
    tableData.value = filteredData;
    total.value = tableData.value.length
    loading.value = false; // 隐藏加载样式
  }, 1000); // 模拟查询耗时 1 秒
};
onMounted(() => {
  // 获取表格数据并备份
  gettableData().then(() => {
    originalTableData.value = [...tableData.value];
    total.value = tableData.value.length;
  });
});

// TODO: 删除功能
const handleDelete = async () => {
  if (selectedRowIds.value.length > 0) {
    const selectedRowCount = selectedRowIds.value.length;
    try {
      const confirmed = await ElMessageBox.confirm(`确定删除这 ${selectedRowCount} 条数据吗？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        top: '10vh',
        lockScroll: false
      });
      if (confirmed) {
        console.log(selectedRowIds.value)
        const response = await axios.delete('http://127.0.0.1:5000/Term/Muser', {
          data: { Ids: selectedRowIds.value }
        });
        gettableData().then(() => {
          originalTableData.value = [...tableData.value];
          total.value = tableData.value.length;
          setTimeout(() => {
            ElMessage({
              type: 'success',
              message: '删除成功！'
            });
        }, 1000); // 设置最低持续时间为 1 秒

  });
        // 在这里执行其他操作，比如重新加载数据等
      } else {
        ElMessage({
          type: 'info',
          message: '取消删除！'
        });
      }
    } catch (error) {
      ElMessage.error('删除失败，请重试！');
      console.error('删除失败：', error);
    }
  }
};

//更新数据
const refreshData = () => {
  gettableData().then(() => {
    originalTableData.value = [...tableData.value];
    total.value = tableData.value.length;
    setTimeout(() => {
      ElMessage({
      type: 'success',
      message: '操作成功！'
    });
    }, 1000); // 设置最低持续时间为 1 秒
  });
};



// TODO: 增加+编辑功能
const edituserRef = ref(null)
const EditUserManage = (row) => {
  edituserRef.value.open(row)
}
// TODO: 增加功能
const adduserRef = ref(null)
const AddUserManage = () => {
  adduserRef.value.open()
}

</script>

<style scoped>
.aa{
  position: absolute;
  width: 84%;
}
.usermanage{
  position: relative;
  height: 520px;
  width: 100%;

}
 .msg{
  position: relative;
  font-size: 20px;
  margin-top: 25px;
  border-bottom:1px solid #dec4c4;
}
.table_top{
  position: relative;
  height:50px;
  width: 100%;
  background-color: rgb(219, 222, 222);
  float: left;
  margin-top: 6px;
}
.table_top .input_{
  width:15%;
  float: right;
  display: flex; 
  padding-top: 10px;
  margin-right: 5px;
}
.table_bottom{
  position: relative;
  height:50px;
  width: 100%;
  background-color: rgb(200, 210, 210);
  float: left;
}
.ml-4{
  position:relative;
  float: left;
  padding-top:8px;
}
.btn-left{
  position:relative;
  padding-top:8px;
 float: right;
}
.example-showcase .el-loading-mask {
  z-index: 9;
}
</style>